package com.che.software.testato.web.controller;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.event.ActionEvent;

import org.apache.log4j.Logger;
import org.primefaces.context.RequestContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.che.software.testato.business.ProjectManager;
import com.che.software.testato.business.VersionManager;
import com.che.software.testato.business.exception.ProjectCreationManagerException;
import com.che.software.testato.business.exception.ProjectSearchManagerException;
import com.che.software.testato.business.exception.VersionCreationManagerException;
import com.che.software.testato.business.exception.VersionSearchManagerException;
import com.che.software.testato.domain.entity.Project;
import com.che.software.testato.domain.entity.Version;
import com.che.software.testato.domain.entity.VersionedProject;
import com.che.software.testato.domain.entity.search.ProjectSearch;
import com.che.software.testato.web.controller.acontroller.AbstractController;

/**
 * Controller used to manage the projects administration.
 * 
 * @author Clement HELIOU (clement.heliou@che-software.com).
 * @copyright Che Software.
 * @license GNU General Public License.
 * @see AbstractController, Serializable.
 * @since July, 2011.
 * 
 *        This file is part of Testato.
 * 
 *        Testato is free software: you can redistribute it and/or modify it
 *        under the terms of the GNU General Public License as published by the
 *        Free Software Foundation, either version 3 of the License, or (at your
 *        option) any later version.
 * 
 *        Testato is distributed in the hope that it will be useful, but WITHOUT
 *        ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 *        FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
 *        for more details.
 * 
 *        You should have received a copy of the GNU General Public License
 *        along with Testato. If not, see <http://www.gnu.org/licenses/>.
 * 
 *        Testato's logo is a creation of Arrioch
 *        (http://arrioch.deviantart.com/) and it's distributed under the terms
 *        of the Creative Commons License.
 */
@Component("projectsAdministrationController")
@ManagedBean(name = "projectsAdministrationController")
@Scope("session")
@SessionScoped
public class ProjectsAdministrationController extends AbstractController implements Serializable {

	/**
	 * Constants.
	 */
	private static final Logger LOGGER = Logger.getLogger(ProjectsAdministrationController.class);
	private static final long serialVersionUID = -2309663193549855909L;

	/**
	 * Members.
	 */
	private Boolean checkExistingProject = false;
	private Project currentProject, projectToCreate;
	@Autowired
	private transient ProjectManager projectManager;
	private List<VersionedProject> projects;
	private Version lastVersion, versionToCreate;
	@Autowired
	private transient VersionManager versionManager;
	private VersionedProject[] selectedProjects;

	/**
	 * Creating the object corresponding to the project to create.
	 * 
	 * @author Clement HELIOU (clement.heliou@che-software.com).
	 * @param ev the event launched during the creation of a project.
	 * @since July, 2011.
	 */
	public void createProject(ActionEvent ev) {
		LOGGER.debug("createProject(" + projectToCreate.getName() + ").");
		try {
			checkExistingProject = projectManager.isProjectExists(projectToCreate.getName());
			if (!checkExistingProject) {
				projectManager.createProjectFromName(projectToCreate.getName());
				projectToCreate = new Project();
				projects = null; // To trigger the data loading.
				RequestContext.getCurrentInstance().addPartialUpdateTarget("projectsForm:projectsTable");
			} else {
				RequestContext.getCurrentInstance().addCallbackParam(NOT_VALID_CALLBACK_PARAM, true);
			}
		} catch (ProjectCreationManagerException e) {
			LOGGER.error("Error during the creation of a project.", e);
			RequestContext.getCurrentInstance().addCallbackParam(NOT_VALID_CALLBACK_PARAM, true);
		} catch (ProjectSearchManagerException e) {
			LOGGER.error("Error during the project existance checking.", e);
			RequestContext.getCurrentInstance().addCallbackParam(NOT_VALID_CALLBACK_PARAM, true);
		}
	}

	/**
	 * Creating the object corresponding to the version to create.
	 * 
	 * @author Clement HELIOU (clement.heliou@che-software.com).
	 * @param ev the event launched during the creation of a version.
	 * @since July, 2011.
	 */
	public void createVersion(ActionEvent ev) {
		LOGGER.debug("createVersion().");
		try {
			versionToCreate.setProjectId(currentProject.getProjectId());
			versionManager.createVersionFromBean(versionToCreate);
			versionToCreate = new Version();
			projects = null; // To trigger the data loading.
			RequestContext.getCurrentInstance().addPartialUpdateTarget("projectsForm:projectsTable");
		} catch (VersionCreationManagerException e) {
			LOGGER.error("Error during the creatin of a version.", e);
			RequestContext.getCurrentInstance().addCallbackParam(NOT_VALID_CALLBACK_PARAM, true);
		}
	}

	/**
	 * Initializing the object corresponding to the project to create.
	 * 
	 * @author Clement HELIOU (clement.heliou@che-software.com).
	 * @param e the event launched during the creation of a project.
	 * @since July, 2011.
	 */
	public void initProjectToCreate(ActionEvent e) {
		LOGGER.debug("initProjectToCreate().");
		checkExistingProject = false;
		projectToCreate = new Project();
	}

	/**
	 * Redirection to perform to get the project page.
	 * 
	 * @author Clement HELIOU (clement.heliou@che-software.com).
	 * @return the resulting redirection.
	 * @since August, 2011.
	 */
	public String onAccess() {
		LOGGER.debug("onAccess().");
		projects = null; // To trigger the data loading.
		selectedProjects = null;
		return "projects.xhtml?faces-redirect=true";
	}

	/**
	 * Action listener on version creation.
	 * 
	 * @author Clement HELIOU (clement.heliou@che-software.com).
	 * @param ev the launched event.
	 * @since July, 2011.
	 */
	public void onVersionCreation(ActionEvent e) {
		LOGGER.debug("onVersionCreation().");
		currentProject = new Project();
		versionToCreate = new Version();
	}

	/**
	 * Getter for the private field value projectManager.
	 * 
	 * @return the projectManager field value.
	 */
	public ProjectManager getProjectManager() {
		return projectManager;
	}

	/**
	 * Setting a value to the projectManager field.
	 * 
	 * @param projectManager the value to set.
	 */
	public void setProjectManager(ProjectManager projectManager) {
		this.projectManager = projectManager;
	}

	/**
	 * Getter for the private field value versionManager.
	 * 
	 * @return the versionManager field value.
	 */
	public VersionManager getVersionManager() {
		return versionManager;
	}

	/**
	 * Setting a value to the versionManager field.
	 * 
	 * @param versionManager the value to set.
	 */
	public void setVersionManager(VersionManager versionManager) {
		this.versionManager = versionManager;
	}

	/**
	 * Getter for the private field value projects.
	 * 
	 * @return the projects field value.
	 */
	public List<VersionedProject> getProjects() {
		if (null == projects) {
			LOGGER.debug("getProjects(): initialization.");
			List<VersionedProject> result = new ArrayList<VersionedProject>();
			try {
				for (Project project : projectManager.searchProject(new ProjectSearch())) {
					result.add(new VersionedProject(versionManager.getVersionsNumberFromProjectId(project.getProjectId()), project, versionManager.getLastVersionFromProjectId(project.getProjectId())));
				}
			} catch (ProjectSearchManagerException e) {
				LOGGER.error("Error during a project search.", e);
			} catch (VersionSearchManagerException e) {
				LOGGER.error("Error during a version search.", e);
			}
			projects = result;
		}
		return projects;
	}

	/**
	 * Setting a value to the projects field.
	 * 
	 * @param projects the value to set.
	 */
	public void setProjects(List<VersionedProject> projects) {
		this.projects = projects;
	}

	/**
	 * Getter for the private field value selectedProjects.
	 * 
	 * @return the selectedProjects field value.
	 */
	public VersionedProject[] getSelectedProjects() {
		return selectedProjects;
	}

	/**
	 * Setting a value to the selectedProjects field.
	 * 
	 * @param selectedProjects the value to set.
	 */
	public void setSelectedProjects(VersionedProject[] selectedProjects) {
		this.selectedProjects = selectedProjects;
	}

	/**
	 * Getter for the private field value projectToCreate.
	 * 
	 * @return the projectToCreate field value.
	 */
	public Project getProjectToCreate() {
		return projectToCreate;
	}

	/**
	 * Setting a value to the projectToCreate field.
	 * 
	 * @param projectToCreate the value to set.
	 */
	public void setProjectToCreate(Project projectToCreate) {
		this.projectToCreate = projectToCreate;
	}

	/**
	 * Getter for the private field value checkExistingProject.
	 * 
	 * @return the checkExistingProject field value.
	 */
	public Boolean getCheckExistingProject() {
		return checkExistingProject;
	}

	/**
	 * Setting a value to the checkExistingProject field.
	 * 
	 * @param checkExistingProject the value to set.
	 */
	public void setCheckExistingProject(Boolean checkExistingProject) {
		this.checkExistingProject = checkExistingProject;
	}

	/**
	 * Getter for the private field value currentProject.
	 * 
	 * @return the currentProject field value.
	 */
	public Project getCurrentProject() {
		return currentProject;
	}

	/**
	 * Setting a value to the currentProject field.
	 * 
	 * @param currentProject the value to set.
	 */
	public void setCurrentProject(Project currentProject) {
		this.currentProject = currentProject;
	}

	/**
	 * Getter for the private field value versionToCreate.
	 * 
	 * @return the versionToCreate field value.
	 */
	public Version getVersionToCreate() {
		return versionToCreate;
	}

	/**
	 * Setting a value to the versionToCreate field.
	 * 
	 * @param versionToCreate the value to set.
	 */
	public void setVersionToCreate(Version versionToCreate) {
		this.versionToCreate = versionToCreate;
	}

	/**
	 * Getter for the private field value lastVersion.
	 * 
	 * @return the lastVersion field value.
	 */
	public Version getLastVersion() {
		return lastVersion;
	}

	/**
	 * Setting a value to the lastVersion field.
	 * 
	 * @param lastVersion the value to set.
	 */
	public void setLastVersion(Version lastVersion) {
		this.lastVersion = lastVersion;
	}
}